package com.XinYun.Library.modules.admin.upload.service;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.servlet.multipart.MultipartFormData;
import cn.hutool.extra.servlet.multipart.MultipartRequestInputStream;
import cn.hutool.extra.servlet.multipart.UploadFile;
import com.XinYun.Library.modules.admin.common.AdminReturnCode;
import com.XinYun.Library.modules.admin.common.BasicService;
import com.XinYun.Library.modules.admin.upload.UploadServlet;
import com.XinYun.Library.modules.commons.BasicJson;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class UploadService extends BasicService {

    static Properties properties = new Properties();

    static {
        try{
            properties.load(new FileInputStream(UploadServlet.class.getClassLoader().getResource("OSSConfig.properties").getPath()));
        }catch (Exception e ){
            throw new RuntimeException("Read Exception");
        }
    }

    /*上传图篇*/
    public void uploadImg(HttpServletRequest req, HttpServletResponse resp, BasicJson json) throws ServletException, IOException{
        MultipartRequestInputStream multiIS = new MultipartRequestInputStream(req.getInputStream());
        MultipartFormData multipart = ServletUtil.getMultipart(req);
        UploadFile img = multipart.getFile("img");
        //校验是否为图片
        if (img.getFileName().matches("(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)")){
            try {
                //上传
                String url = uploadToOSS(img);
                setMsgCode(json, AdminReturnCode.SUCCECSS);
                json.setData(url);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            setMsgCode(json, AdminReturnCode.ERR_WRONG_PARAM);
        }
    }

    /**
     * 来自Aliyun官方给出的OSS SDK使用演示
     * @param uploadFile
     * @throws Exception
     */
    public String uploadToOSS(UploadFile uploadFile) throws Exception {
        // Endpoint以北京
        String endpoint = properties.getProperty("endpoint");
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId =  properties.getProperty("accessKeyId");
        String accessKeySecret =  properties.getProperty("accessKeySecret");
        // 填写Bucket名称，例如examplebucket。
        String bucketName =  properties.getProperty("bucketName");
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = uploadFile.getFileName();
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, uploadFile.getFileInputStream());
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);
            // 上传文件。
            ossClient.putObject(putObjectRequest);
            System.out.println("上传成功");
            return "http://"+bucketName+"."+endpoint.substring(8)+"/"+ URLUtil.encode(objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
